package com.cn.suplayer;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;


import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;


/**
 * 记录错误信息，当程序发生异常崩溃的时候。到这个界面。
 */
public class CrashActivity extends Activity {

	TextView tv_ExceptionTrace;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTheme(android.R.style.Theme_Black_NoTitleBar);
		initWidgets();

		Intent intent = getIntent();
		if (intent != null) {
			Throwable ex = (Throwable) intent.getSerializableExtra("exception");
			// App onCreate 过程中发生的异常直接忽略，否则造成循环进入。
			StringWriter sw = new StringWriter();
			PrintWriter printWriter = new PrintWriter(sw);
			ex.printStackTrace(printWriter);
			tv_ExceptionTrace.setText("开发版本错误\n"
					+ sw.toString());
			// tv_ExceptionTrace.setText("开发版本错误，请您反馈给技术支持人员");
			try {
				sw.close();
				printWriter.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private void initWidgets() {

		LinearLayout linearRoot = new LinearLayout(this);
		linearRoot.setOrientation(LinearLayout.VERTICAL);

		Button btn_Close = new Button(this);
		btn_Close.setText("Close");
		btn_Close.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				android.os.Process.killProcess(android.os.Process.myPid());
				Log.i("","Crash Task ID : " + getTaskId());
			}
		});

		tv_ExceptionTrace = new TextView(this);
		tv_ExceptionTrace.setFocusable(false);
		// tv_ExceptionTrace.setEnabled(false);
		tv_ExceptionTrace.setVerticalScrollBarEnabled(true);
		tv_ExceptionTrace.setMovementMethod(ScrollingMovementMethod
				.getInstance());
		ScrollView scroll = new ScrollView(this);
		scroll.addView(tv_ExceptionTrace);
		linearRoot.addView(btn_Close, -1, -2);
		linearRoot.addView(scroll, -2, -1);

		setContentView(linearRoot, new ViewGroup.LayoutParams(-1, -1));
	}

	public void onClick(View v) {

		// App app = (App) getApplication();
		// app.exit();
		// startActivity(new Intent(this, LaunchActivity.class));
		// finish();
		android.os.Process.killProcess(android.os.Process.myPid());
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
			android.os.Process.killProcess(android.os.Process.myPid());
		return true;
	}
	
}